package com.neiquan.weiguan.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.neiquan.weiguan.R;
import com.neiquan.weiguan.adapter.DragAdapter;
import com.neiquan.weiguan.adapter.OtherAdapter;
import com.neiquan.weiguan.bean.ChannelItem;
import com.neiquan.weiguan.fragment.base.AppBaseFragment;
import com.neiquan.weiguan.fragment.view.EditMenuFragmentView;
import com.neiquan.weiguan.presenter.ChannelPresenter;
import com.neiquan.weiguan.utils.Constant;
import com.neiquan.weiguan.widget.DragGrid;

import net.neiquan.applibrary.utils.LogC;
import net.neiquan.applibrary.wight.NoScrollGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 编辑 菜单
 */
public class EditMenuFragment extends AppBaseFragment implements OnItemClickListener, DragGrid.OnDragGridItemMoveListener, EditMenuFragmentView {

    @InjectView(R.id.userGridView)
    DragGrid mUserGridView;
    @InjectView(R.id.otherGridView)
    NoScrollGridView mOtherGridView;
    /**
     * 用户栏目对应的适配器，可以拖动
     */
    DragAdapter userAdapter;
    /**
     * 其它栏目对应的适配器
     */
    OtherAdapter otherAdapter;
    /**
     * 其它栏目列表
     */
    ArrayList<ChannelItem> otherChannelList = new ArrayList<ChannelItem>();
    /**
     * 用户栏目列表
     */
    ArrayList<ChannelItem> userChannelList = new ArrayList<ChannelItem>();
    /**
     * 是否在移动，由于这边是动画结束后才进行的数据更替，设置这个限制为了避免操作太频繁造成的数据错乱。
     */
    boolean isMove = false;
    @InjectView(R.id.img_del)
    ImageView mImgDel;
    @InjectView(R.id.my_category_tip_text)
    TextView mMyCategoryTipText;
    private ChannelPresenter channelPresenter;
    /**
     * 数据是否发生改变
     */
    private boolean dataChange = false;

    @Override
    public View initRootView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_editmenu, null);
        ButterKnife.inject(this, view);
        return view;
    }

    @Override
    public void setViews() {

    }

    @Override
    public void initData() {
        channelPresenter = new ChannelPresenter(getActivity(), this);
        channelPresenter.getUserChannel();
        channelPresenter.getOtherChannel();
        userAdapter = new DragAdapter(getActivity(), userChannelList);
        mUserGridView.setAdapter(userAdapter);
        mUserGridView.setEditBtn(mMyCategoryTipText);
        otherAdapter = new OtherAdapter(getActivity(), otherChannelList);
        mOtherGridView.setAdapter(this.otherAdapter);
        //设置GRIDVIEW的ITEM的点击监听
        mOtherGridView.setOnItemClickListener(this);
        mUserGridView.setOnItemClickListener(this);
        mUserGridView.setOnDragGridItemMoveListener(this);
        mOtherGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (!userAdapter.isDelvisible()) {
                    userAdapter.setDelBtnVisible(true);
                    mMyCategoryTipText.setText(getString(R.string.subscribe_manager_category_info_4));
                }
                return true;
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        //如果点击的时候，之前动画还没结束，那么就让点击事件无效
        if (isMove) {
            return;
        }
        switch (parent.getId()) {
            case R.id.userGridView:
                if (userAdapter.isDelvisible()) {
                    dataChange = true;//数据发生改变
                    //position为 0，1 的不可以进行任何操作
                    if (position != 0 && position != 1) {
                        final ImageView moveImageView = getView(view);
                        if (moveImageView != null) {
                            TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                            final int[] startLocation = new int[2];
                            newTextView.getLocationInWindow(startLocation);
                            final ChannelItem channel = ((DragAdapter) parent.getAdapter()).getItem(position);//获取点击的频道内容
                            otherAdapter.setVisible(false);
                            channel.setSelected(0);
                            //添加到最后一个
                            otherAdapter.addItem(channel);
                            new Handler().postDelayed(new Runnable() {
                                public void run() {
                                    try {
                                        int[] endLocation = new int[2];
                                        //获取终点的坐标
                                        mOtherGridView.getChildAt(mOtherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                        MoveAnim(moveImageView, startLocation, endLocation, channel, mUserGridView);
                                        userAdapter.setRemove(position);
                                    } catch (Exception localException) {
                                    }
                                }
                            }, 50L);
                        }
                    }
                } else {
                    if (dataChange) {
                        channelPresenter.deleteAllChannel();
                        channelPresenter.saveUserChannel(userAdapter.getChannnelLst());
                        channelPresenter.saveOtherChannel(otherAdapter.getChannnelLst());
                    }
                    Intent intent = new Intent();
                    intent.putExtra("dataChange", dataChange);
                    intent.putExtra("position", position);
                    getActivity().setResult(Constant.ONACTIVITYRESULT_CHANNELSELECT, intent);
                    getActivity().finish();
                }
                break;
            case R.id.otherGridView:
                dataChange = true;//数据发生改变
                final ImageView moveImageView = getView(view);
                if (moveImageView != null) {
                    TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                    final int[] startLocation = new int[2];
                    newTextView.getLocationInWindow(startLocation);
                    final ChannelItem channel = ((OtherAdapter) parent.getAdapter()).getItem(position);
                    channel.setSelected(1);
                    userAdapter.setVisible(false);
                    //添加到最后一个
                    userAdapter.addItem(channel);
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            try {
                                int[] endLocation = new int[2];
                                //获取终点的坐标
                                mUserGridView.getChildAt(mUserGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                MoveAnim(moveImageView, startLocation, endLocation, channel, mOtherGridView);
                                otherAdapter.setRemove(position);
                            } catch (Exception localException) {
                            }
                        }
                    }, 50L);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 点击ITEM移动动画
     *
     * @param moveView
     * @param startLocation
     * @param endLocation
     * @param moveChannel
     * @param clickGridView
     */
    private void MoveAnim(View moveView, int[] startLocation, int[] endLocation, final ChannelItem moveChannel,
                          final GridView clickGridView) {
        int[] initLocation = new int[2];
        //获取传递过来的VIEW的坐标
        moveView.getLocationInWindow(initLocation);
        //得到要移动的VIEW,并放入对应的容器中
        final ViewGroup moveViewGroup = getMoveViewGroup();
        final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
        //创建移动动画
        TranslateAnimation moveAnimation = new TranslateAnimation(
                startLocation[0], endLocation[0], startLocation[1],
                endLocation[1]);
        moveAnimation.setDuration(300L);//动画时间
        //动画配置
        AnimationSet moveAnimationSet = new AnimationSet(true);
        moveAnimationSet.setFillAfter(false);//动画效果执行完毕后，View对象不保留在终止的位置
        moveAnimationSet.addAnimation(moveAnimation);
        mMoveView.startAnimation(moveAnimationSet);
        moveAnimationSet.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                isMove = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                moveViewGroup.removeView(mMoveView);
                // instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
                if (clickGridView instanceof DragGrid) {
                    otherAdapter.setVisible(true);
                    otherAdapter.notifyDataSetChanged();
                    userAdapter.remove();
                } else {
                    userAdapter.setVisible(true);
                    userAdapter.notifyDataSetChanged();
                    otherAdapter.remove();
                }
                isMove = false;
            }
        });
    }

    /**
     * 获取移动的VIEW，放入对应ViewGroup布局容器
     *
     * @param viewGroup
     * @param view
     * @param initLocation
     * @return
     */
    private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
        int x = initLocation[0];
        int y = initLocation[1];
        viewGroup.addView(view);
        LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLayoutParams.leftMargin = x;
        mLayoutParams.topMargin = y;
        view.setLayoutParams(mLayoutParams);
        return view;
    }

    /**
     * 创建移动的ITEM对应的ViewGroup布局容器
     */
    private ViewGroup getMoveViewGroup() {
        ViewGroup moveViewGroup = (ViewGroup) getActivity().getWindow().getDecorView();
        LinearLayout moveLinearLayout = new LinearLayout(getActivity());
        moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        moveViewGroup.addView(moveLinearLayout);
        return moveLinearLayout;
    }

    /**
     * 获取点击的Item的对应View，
     *
     * @param view
     * @return
     */
    private ImageView getView(View view) {
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(true);
        Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        ImageView iv = new ImageView(getActivity());
        iv.setImageBitmap(cache);
        return iv;
    }

    @OnClick({R.id.my_category_tip_text, R.id.img_del})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.my_category_tip_text:
                if (userAdapter.isDelvisible()) {
                    mMyCategoryTipText.setText(getString(R.string.subscribe_manager_category_info_3));
                } else {
                    mMyCategoryTipText.setText(getString(R.string.subscribe_manager_category_info_4));
                }
                userAdapter.setDelBtnVisible(!userAdapter.isDelvisible());
                break;
            case R.id.img_del:
                saveData();
                break;
        }
    }

    /**
     * 退出时候
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                saveData();
                break;
        }
        return true;
    }

    /**
     * 保存选择后数据库的设置
     */
    private void saveData() {
        Intent intent = new Intent();
        intent.putExtra("dataChange", dataChange);
        if (dataChange) {
            channelPresenter.deleteAllChannel();
            channelPresenter.saveUserChannel(userAdapter.getChannnelLst());
            channelPresenter.saveOtherChannel(otherAdapter.getChannnelLst());
        }
        getActivity().setResult(Constant.ONACTIVITYRESULT_CHANNEL, intent);
        getActivity().finish();
    }

    @Override
    public void getUserMenus(List<ChannelItem> channelItems) {
        userChannelList = (ArrayList<ChannelItem>) channelItems;
    }

    @Override
    public void getOtherMenus(List<ChannelItem> channelItems) {
        otherChannelList = (ArrayList<ChannelItem>) channelItems;
    }

    @Override
    public void OnMove(int position) {
        dataChange = true;//数据发生改变
    }
}
